package com.toket.android.pushme.screen;

import static com.toket.android.pushme.gcm.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.toket.android.pushme.gcm.CommonUtilities.EXTRA_MESSAGE;
import static com.toket.android.pushme.gcm.CommonUtilities.SENDER_ID;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.toket.android.pushme.R;
import com.toket.android.pushme.activity.PushMeActivity;
import com.toket.android.pushme.gcm.WakeLocker;
import com.toket.android.pushme.parser.JSONParser;
import com.toket.android.utils.ApplicationConfigs;
import com.toket.android.utils.Shared;

public class LoginScreen extends PushMeActivity implements OnClickListener {

	public static Context mContext;
	
	private SharedPreferences setting;
	
	private EditText edit_username, edit_password;
	private ImageView check_remember_me;
	private ImageView btn_login;
	private TextView text_register;
	
	private boolean isRememberMe = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		try {
			Class.forName("android.os.AsyncTask");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_screen);
		
		setting = getSharedPreferences(Shared.SHARED_NAME, MODE_PRIVATE);
		mContext = this;
		
		initActivity();

	}

	@Override
	protected void initLayout() {
		// TODO Auto-generated method stub
		edit_username = (EditText) findViewById(R.id.edit_username);
		edit_password = (EditText) findViewById(R.id.edit_password);

		check_remember_me = (ImageView) findViewById(R.id.check_remember_me);

		btn_login = (ImageView) findViewById(R.id.btn_login);

		text_register = (TextView) findViewById(R.id.text_register);
	}

	@Override
	protected void initValue() {
		// TODO Auto-generated method stub
		
		edit_password.setTypeface(Typeface.DEFAULT);
		edit_password.setTransformationMethod(new PasswordTransformationMethod());
		edit_password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
	        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
	            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_UNSPECIFIED
	            		|| actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_NEXT
	            		|| actionId == EditorInfo.IME_ACTION_NONE || actionId == EditorInfo.IME_ACTION_SEND) {
	            	// hide virtual keyboard
	                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
	                imm.hideSoftInputFromWindow(edit_password.getWindowToken(), 0);
	                
//	                if(event != null && event.getAction() == KeyEvent.ACTION_UP){
//	                	login();
//	                }
	                
	                return true;
	            }
	            return false;
	        }
	    });
		
		String htmlString = "<u>" + getResources().getText(R.string.register)
				+ "</u>";

		text_register.setText(Html.fromHtml(htmlString));
		
		check_remember_me.setOnClickListener(this);
		btn_login.setOnClickListener(this);
		text_register.setOnClickListener(this);
	}

	@Override
	protected void cleanUp() {
		// TODO Auto-generated method stub
		mContext = null;
		try {
			unregisterReceiver(mHandleMessageReceiver);
			GCMRegistrar.onDestroy(this);
		} catch (Exception e) {
			Log.e("UnRegister Receiver Error", "> " + e.getMessage());
		}
	}

	private void login() {
		// hide virtual keyboard
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edit_password.getWindowToken(), 0);
        
		showProgressDialog("", getResources().getString(R.string.loading), true);

		String username = setting.getString(Shared.PREF_USERNAME, Shared.DEFAULT_USERNAME);
		String token_id = setting.getString(Shared.PREF_AUTH_ID, Shared.DEFAULT_AUTH_ID);
		String sender_email = setting.getString(Shared.PREF_SENDER_EMAIL, Shared.DEFAULT_SENDER_EMAIL);
		
		if((!username.trim().isEmpty() && username.trim().length() != 0 &&
				!username.equalsIgnoreCase(edit_username.getText().toString())) ||
				!sender_email.equalsIgnoreCase(ApplicationConfigs.SENDER_EMAIL)){
			
//			Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
//			intent.putExtra("app",
//					PendingIntent.getBroadcast(this, 0, new Intent(), 0));
//			intent.putExtra("sender", ApplicationConfigs.SENDER_EMAIL);
//			startService(intent);
			
			// Make sure the device has the proper dependencies.
			GCMRegistrar.checkDevice(this);

			// Make sure the manifest was properly set - comment out this line
			// while developing the app, then uncomment it when it's ready.
			GCMRegistrar.checkManifest(this);
			
			registerReceiver(mHandleMessageReceiver, new IntentFilter(
					DISPLAY_MESSAGE_ACTION));
			// Get GCM registration id
			final String regId = GCMRegistrar.getRegistrationId(this);
			
			// Check if regid already presents
			if (regId.equals("")) {System.out.println("## gen new Registeration ID ##");
				// Registration is not present, register now with GCM
				GCMRegistrar.register(this, SENDER_ID);
			} else {System.out.println("## gen new Registeration ID2 ##");
				if (GCMRegistrar.isRegisteredOnServer(this)) {
					// Skips registration.
					startFeedLogin(regId);
				} else {
					// Try to register again, but not in the UI thread.
					// It's also necessary to cancel the thread onDestroy(),
					// hence the use of AsyncTask instead of a raw thread.
					startFeedLogin(regId);
				}
			}
			
		}else{
			startFeedLogin(token_id);
		}
		
	}
	
	/**
	 * Receiving push messages
	 * */
	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
			// Waking up mobile if it is sleeping
			WakeLocker.acquire(getApplicationContext());

			/**
			 * Take appropriate action on this message depending upon your app
			 * requirement For now i am just displaying it on the screen
			 * */

			// Showing received message
			Toast.makeText(getApplicationContext(),
					"New Message: " + newMessage, Toast.LENGTH_LONG).show();

			// Releasing wake lock
			WakeLocker.release();
		}
	};

	public void startFeedLogin(String token_id){
//		Toast.makeText(mContext, token_id, Toast.LENGTH_LONG).show();
//		Looper looper = Looper.getMainLooper();
//	    Handler handler = new Handler(looper);
//	    handler.post(new Runnable() {
//	      public void run() {
//	        try {
//	          Class.forName("android.os.AsyncTask");
//	        } catch (ClassNotFoundException e) {
//	          e.printStackTrace();
//	        }
//	      }
//	    });
	    
		FeedLogin feedlogin = new FeedLogin(
				edit_username.getText().toString(),
				edit_password.getText().toString(), 
				token_id);
		feedlogin.execute("");
	}
	
	private class FeedLogin extends AsyncTask<String, Void, Boolean> {
		
		private String url_;
		private String username;
		
		public FeedLogin(String username, String password, String token_id) {
			url_ = ApplicationConfigs.URL_LOGIN + 
					"/user/" + username + 
					"/pass/" + password + 
					"/token_id/" + token_id;
			
			this.username = username;
		}

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			JSONParser parser = new JSONParser(url_);
			boolean result = parser.connectInputStream();
			if(result){
				result = parser.feedLoginData();
			}
			return result;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			System.out.println("## BEFORE");
			Editor edit = setting.edit();
			edit.putString(Shared.PREF_USERNAME, username);
			edit.putBoolean(Shared.PREF_ISREMEMBER, isRememberMe);
			edit.putBoolean(Shared.PREF_ISLOGIN, result);
			edit.putString(Shared.PREF_SENDER_EMAIL, ApplicationConfigs.SENDER_EMAIL);
			edit.commit();
			System.out.println("## AFTER");
			dismissProgressDialog();
			
			if (result) {
//				Toast.makeText(mContext, getResources().getString(R.string.login_success), Toast.LENGTH_LONG).show();
				Intent goToScreen = new Intent(mContext, MainScreen.class);
				startActivity(goToScreen);
				finish();
			}else{
//				Toast.makeText(mContext, getResources().getString(R.string.login_fail), Toast.LENGTH_LONG).show();
			}

		}
		
	}
	
	private void register() {

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.check_remember_me:
			if(isRememberMe){
				isRememberMe = false;
				check_remember_me.setImageResource(R.drawable.remember_me_uncheck);
			}else{
				isRememberMe = true;
				check_remember_me.setImageResource(R.drawable.remember_me_check);
			}
			break;
		case R.id.btn_login:
			login();
			break;
		case R.id.text_register:
			register();
			break;
		}
	}

}
